package com.ase.javabase.锁;

/**
 * @author gyhstart
 * @create 2021/3/8 - 22:23
 **/
public class SynchronizedTest {

    //定义个year，用来记录某明星的练习年数
    private static double year;

    public void run() {
        //线程A，练习唱跳rap
        Thread threadA = new Thread(() -> {
            synchronized (this) {
                for (year = 0.5; year <= 5; year += 0.5) {
                    System.out.println("蔡徐鸡开始练习唱跳rap：已练习" + year + "年");
                    try {
                        Thread.sleep(288);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //众所周知，练习两年半即可出道
                    if (year == 2.5) {
                        System.out.println("===========================>成功练习两年半，出道！！！");
                        this.notify();
                    }
                }
            }
        });
        //线程B，练习打篮球
        Thread threadB = new Thread(() -> {
            while (true) {
                synchronized (this) {
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("蔡徐鸡开始练习打篮球");
                }
            }
        });
        //注意，一定要先启动B，不然会导致B永远拿不到锁
        threadB.start();
        threadA.start();
    }

    public static void main(String[] args) {
        SynchronizedTest test = new SynchronizedTest();
        test.run();
    }
}

